<template>
    <view class="container">
        <view class="task_type_list">
            <scroll-view scroll-x class="tab-h" :scroll-into-view="'tab_'+positionTab" scroll-with-animation='true'>
              <view  v-for="(item,index) in taskStateList" :key="index" @tap='bindTypeItem(index)' :id="'tab_'+item.id" class='tab-item' :style="{color:positionTab==index?defaultColor:'',}">
                {{item.name}}
                <text class="active_border" :style="{borderBottom:'4rpx solid '+defaultColor}" v-if="positionTab==index"></text>
              </view>
            </scroll-view>
        </view>
        <view class="task_list" v-if="taskList&&taskList.length!=0">
            <view class="task_item" v-for="(item,index) in taskList" :key="index" :data-url="'task_detail.html?taskId='+item.id" @tap="tolinkUrl">
                <view class="task_item_top">
                    <text class="task_type_tag" :style="{background:defaultColor}" v-if="item.topOrder>0">顶</text>
                    <text class="task_type_tag" :style="{background:defaultColor}" v-if="item.taskMode==1">抢单</text>
                    <text class="task_type_tag" :style="{background:defaultColor}" v-if="item.taskMode==2">预选</text>
                    <text class="task_item_price" :style="{color:defaultColor}" v-if="item.priceMode==0">免费</text>
                    <text class="task_item_price" :style="{color:defaultColor}" v-if="item.priceMode==1">可议价</text>
                    <text class="task_item_price" :style="{color:defaultColor}" v-if="item.priceMode==2">￥{{item.taskPrice}}</text>
                    <text class="task_item_name">{{item.name}}</text>
                    <image class="hb_block" v-if="item.tipPrice" src="https://image1.sansancloud.com/xianhua/2020_5/8/10/20/37_663.jpg?x-oss-process=style/preview_120"></image>
                </view>
                <view class="task_item_content">
                    {{item.content}}
                </view>
                <scroll-view class='tags_content' scroll-x v-if="item.tags">
                  <text class='tags_item' :style="{background:defaultColor+22,color:defaultColor}" v-for='(item,index) in item.managerTagArray' :key='index'>{{item}}</text>
                  <text class='tags_item' style="border: 1rpx solid #eee;" v-for='(item,index) in item.tagArray' :key='index'>{{item}}</text>
                </scroll-view>
                <view class="task_item_bottom">
                    <view class="task_item_attend_count">终选<text :style="{color:defaultColor,margin:'0 4rpx'}">{{item.taskServantCount||0}}</text>人</view>
                    <view class="task_item_state">
                        <text class="task_item_state_text" v-if="item.taskStatus==0">未发布</text>
                        <text class="task_item_state_text" v-if="item.taskStatus==1">待审核</text>
                        <text class="task_item_state_text" v-if="item.taskStatus==2">审核拒绝</text>
                        <text class="task_item_state_text" v-if="item.taskStatus==3">{{item.taskEndTime||'不限期'}}截止</text>
                        <text class="task_item_state_text" v-if="item.taskStatus==4">任务进行中</text>
                        <text class="task_item_state_text" v-if="item.taskStatus==5">待验收</text>
                        <text class="task_item_state_text" v-if="item.taskStatus==6">已完成</text>
                    </view>
                </view>
                <view class="task_item_fun_block">
                    <!-- ||item.taskStatus>=3 -->
                    <view class="task_item_fun_list">
                        <view class="task_item_fun_item" @click.stop="sureHandleTaskFun('cancel',item.id)" v-if="item.taskStatus==1">
                            <text class="task_item_fun_item_text">取消任务</text>
                        </view>
                        <view class="task_item_fun_item" @click.stop="sureHandleTaskFun('stop',item.id)" v-if="item.taskStatus==4">
                            <text class="task_item_fun_item_text">暂停报名</text>
                        </view>
                        <view class="task_item_fun_item" @click.stop="sureHandleTaskFun('createProtectedOrder',item.id)" v-if="item.payedStatus==0&&item.needPayedType==2">
                            <text class="task_item_fun_item_text">支付保证金</text>
                        </view>
                        <view class="task_item_fun_item" @click.stop="sureHandleTaskFun('createTaskOrder',item.id)" v-if="item.payedStatus==0&&item.needPayedType==1">
                            <text class="task_item_fun_item_text">支付任务金</text>
                        </view>
                        <view class="task_item_fun_item" @click.stop="tolinkUrl('create_task.html?taskTypeId='+item.belongTaskTypeId)" >
                            <text class="task_item_fun_item_text">快捷发布</text>
                        </view>
                       <!-- <view class="task_item_fun_item" @click.stop="sureHandleTaskFun('finish',item.id)" v-if="item.taskStatus==4">
                            <text class="task_item_fun_item_text">完成任务</text>
                        </view> -->
                        <!-- <view class="task_item_fun_item" @click.stop="sureHandleTaskFun('check',item.id)" v-if="item.taskStatus>=3">
                            <text class="task_item_fun_item_text">参与列表</text>
                        </view> -->
                    </view>
                </view>
            </view>
        </view>
        <view class="noproduct" v-else>
          <image mode="widthFix" src='https://image1.sansancloud.com/xianhua/2019_12/16/15/54/55_950.jpg?x-oss-process=style/preview_120'></image>
          <text>没有相关任务</text>
        </view>
    </view>
</template>

<script>
import { socketFun } from "../../wxcomponents/public/json2Form";
export default {
  data() {
    return {
      taskList:null,
      taskTypeList:[],
      setting:null,
      positionTab:0,
      listPage:{
          page: 1,
          pageSize: 20,
          totalSize: 0,
          taskTypeId: "",
          taskStatus:-1
      },
      taskStateList:[
          {name:'全部',state:-1},
          {name:'待审核',state:1},
          {name:'报名中',state:3},
          {name:'进行中',state:4},
          {name:'待验收',state:5},
          {name:'已完成',state:6},
      ],
      secondColor:'',
      defaultColor:'',
    };
  },
  props: {},

  /*onload*/
  onLoad: function (options) {
    let that=this;
    console.warn("======onLoad:options======", options, getApp().globalData.setting);
    // that.getTypeData();
    that.getData(that.listPage,'upload');
  },
  onReady: function () {
    
  },
  onShow: function () {
    let that=this;
	that.setData({
        setting:getApp().globalData.setting,
        defaultColor:getApp().globalData.setting.platformSetting.defaultColor,
        secondColor:getApp().globalData.setting.platformSetting.secondColor,
       })
  },
  /* 分享 app.js862行*/
  onShareAppMessage: function () {
    console.log(getApp().globalData.miniIndexPage);
    return getApp().globalData.shareForFx2(getApp().globalData.miniIndexPage);
  },
  onPullDownRefresh: function () {
    let that = this; // 下拉刷新的时候首先判断存不存在tab
    console.log("下拉");
    that.listPage.page=1
    that.getData(that.listPage);
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('===onReachBottom====');
    let that = this
    if (that.listPage.totalSize > that.listPage.page * that.listPage.pageSize) {
      that.listPage.page++
      that.getData(that.listPage,'upload');
    }else{
        wx.showToast({
          title: "到底了~",
          image: '/wxcomponents/images/icons/tip.png',
          duration: 1000
        });
    }
  },
  methods: {
    sureHandleTaskFun:function(state,id){
        let that=this;
        let title='您确定要取消该任务吗？'
        if(state=='stop'){
            title="您确定要暂停该任务吗"
        }else if(state=='finish'){
            title="您确定要完成该任务吗"
        }else if(state=='createProtectedOrder'){
             title="您确定要支付保证金吗？"
        }else if(state=='createTaskOrder'){
             title="您确定要支付任务金吗？"
        }
        wx.showModal({
          title: '提示',
          content: title,
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              if(state=='stop'){
                that.stopTaskFun(id)
              }else if(state=='finish'){
                  that.finishTaskFun(id)
              }else if(state=='createProtectedOrder'||state=='createTaskOrder'){
                  that.createTaskOrderFun(state,id)
              } else{
                that.cancelTaskFun(id)
              }
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
    },
    createTaskOrderFun: function (state,id) {
      var that = this;
      let wxChatPayParam = {
        payType: 3,
        taskId:id,
      };
      let reqUrl="/wx_create_task_order.html";
      if(state=='createProtectedOrder'){
        reqUrl="/wx_create_task_protected_order.html";
      }
      let customIndex = getApp().globalData.AddClientUrl(reqUrl, wxChatPayParam, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res.data); //这里拿到订单数据
          //下面应该吊起支付
          console.log(res.data);
          let orderNo = res.data.relateObj.orderNo;
          if(res.data.errcode==0){
            // that.payByWechat(orderNo);
            let url='edit_order.html?orderNo='+orderNo;
            that.tolinkUrl(url)
          }
        },
        fail: function () {},
        complete: function () {
        }
      });
    },
    // payByWechat: function (orderNo) {
    //   var that = this;
    //   let loginUser = getApp().globalData.loginUser;
    //   console.log(loginUser);
    //   let wxChatPayParam = {
    //     openid: loginUser.platformUser.miniOpenId,
    //     orderNo: orderNo,
    //     app: 3
    //   };
    //   let customIndex = getApp().globalData.AddClientUrl("/unifined_order.html", wxChatPayParam, 'post');
    //   wx.request({
    //     url: customIndex.url,
    //     data: customIndex.params,
    //     header: getApp().globalData.headerPost,
    //     method: 'POST',
    //     success: function (res) {
    //       console.log(res.data);
    //       let PayStr = res.data;
    //       PayStr = '{' + PayStr + '}';
    //       let wechatPayStr = JSON.parse(PayStr);
    //       console.log(wechatPayStr);
    //       wx.requestPayment({
    //         'timeStamp': wechatPayStr.timeStamp,
    //         'nonceStr': wechatPayStr.nonceStr,
    //         'package': wechatPayStr.package,
    //         'signType': wechatPayStr.signType,
    //         'paySign': wechatPayStr.paySign,
    //         'success': function (res) {
    //           console.log('------成功--------');
    //           console.log(res);
    //           wx.showToast({
    //             title: '支付成功',
    //             icon: 'success',
    //             duration: 2000
    //           });
    //         },
    //         'fail': function (res) {
    //           console.log('------fail--------');
    //           console.log(res);
    //           wx.showToast({
    //             title: '支付失败',
    //             image: '/wxcomponents/images/icons/tip.png',
    //             duration: 2000
    //           });
    //         },
    //         'complete': function () {
    //           console.log('------complete--------');
    //           console.log(res);
    //           // getApp().globalData.navigateBack(2000);
    //           that.getData(that.listPage,'upload');
    //         }
    //       });
    //     }
    //   });
    // },
    cancelTaskFun:function(taskId){
      let that = this
      let params={
          taskId:taskId
      }
      console.log("===params==",params)
      var customIndex = getApp().globalData.AddClientUrl("/wx_cancel_task.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj;
          if(res.data.errcode==0){
              wx.showToast({
                title: "取消成功",
                icon:'success',
                duration: 1000
              });
              // setTimeout(function(){
              //   that.findAttendTaskUserListFun(that.listPage)
              // },1000)
          }else{
              wx.showToast({
                title: res.data.errMsg,
                image: '/wxcomponents/images/icons/tip.png',
                duration: 1000
              });
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    stopTaskFun:function(taskId){
      let that = this
      let params={
          taskId:taskId
      }
      console.log("===params==",params)
      var customIndex = getApp().globalData.AddClientUrl("/wx_stop_task.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj;
          if(res.data.errcode==0){
              wx.showToast({
                title: "暂停成功",
                icon:'success',
                duration: 1000
              });
              // setTimeout(function(){
              //   that.findAttendTaskUserListFun(that.listPage)
              // },1000)
          }else{
              wx.showToast({
                title: res.data.errMsg,
                image: '/wxcomponents/images/icons/tip.png',
                duration: 1000
              });
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    finishTaskFun:function(taskId){
      let that = this
      let params={
          taskId:taskId
      }
      console.log("===params==",params)
      var customIndex = getApp().globalData.AddClientUrl("/wx_task_attend_finished_confirm.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj;
          if(res.data.errcode==0){
              wx.showToast({
                title: "完成成功",
                icon:'success',
                duration: 1000
              });
              // setTimeout(function(){
              //   that.findAttendTaskUserListFun(that.listPage)
              // },1000)
          }else{
              wx.showToast({
                title: res.data.errMsg,
                image: '/wxcomponents/images/icons/tip.png',
                duration: 1000
              });
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    bindTypeItem:function(index){
        let that=this;
        that.positionTab=index
        that.listPage.taskStatus=that.taskStateList[index].state
        that.getData(that.listPage,'upload');
    },
    /* 获取数据 */
    getData: function (param) {
      var that = this
      let params=Object.assign({},param,{
        // taskStatus:-1
      })
      console.log("===params==",params)
      var customIndex = getApp().globalData.AddClientUrl("/wx_find_user_tasks.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj.result
          that.listPage.pageSize = res.data.relateObj.pageSize
          that.listPage.page = res.data.relateObj.curPage
          that.listPage.totalSize = res.data.relateObj.totalSize
          let dataArr = that.taskList;
          let tagArray=[];
          for (let i = 0; i < data.length; i++) {
            if (data[i].tags && data[i].tags != '') {
              tagArray = JSON.parse(data[i].tags)
              data[i].tagArray = tagArray;
            }
            if (data[i].managerTags && data[i].managerTags != '') {
              tagArray = JSON.parse(data[i].managerTags)
              if(data[i].payedPrice>0){
                  tagArray.splice(tagArray.length,1,'已交定金')
              }
              data[i].managerTagArray = tagArray;
            }
          }
          console.log("===data====",data)
          if (param.page == 1) {
            dataArr = []
          }
          if (!data || data.length == 0) {
            that.setData({ taskList: null })
          } else {
            if (dataArr == null) { dataArr = [] }
            dataArr = dataArr.concat(data)
            that.setData({ taskList: dataArr })
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    /* 组件事件集合 */
    tolinkUrl: function (e) {
      console.warn("=======e=======", e);
      let linkUrl = e.currentTarget?e.currentTarget.dataset.url:e;
      getApp().globalData.linkEvent(linkUrl);
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>